<template>
    <div>
        <a-row>
            <!-- v-userAuth="'F2'" -->
            <a-row class='mytitle'>
                <div style="cursor: pointer;width: 360px" @click="handleNavigate">
                    <a-icon type="left" />
                    <span>{{ $t('返回') }}</span>
                    <span style="margin-left: 8px;">|</span>
                    <span style="margin-left: 8px">{{ $t('保护任务详情') }}</span>
                    <span style="margin-left: 8px;">/</span>
                    <span style="margin-left: 8px">{{ name }}</span>
                </div>
            </a-row>

            <a-row style="margin:1.5em 1.5em">
                <div style="background-color:white;box-shadow:0 0 6px 2px rgba(0,0,0,0.15);padding-bottom:15px;">
                    <div style="padding:17px 22px;" class="size14 cont">{{ $t('基础信息') }}</div>
                    <div class="line"></div>
                    <div style="padding:17px 22px;">
                        <a-row class="size14">
                            <a-col :span="3" class="shallow">
                                {{ $t('保护任务名称') }}:
                            </a-col>
                            <a-col :span="21" class="cont">
                                {{ projectTask.name }}
                            </a-col>
                        </a-row>
                        <a-row class="size14 mt-14">
                            <a-col :span="3" class="shallow">
                                {{ $t('保护策略') }}:
                            </a-col>
                            <a-col :span="21" class="cont">
                                {{ projectStrategy.name }}
                            </a-col>
                        </a-row>
                        <a-row class="size14 mt-14">
                            <a-col :span="3" class="shallow">
                                {{ $t('保护任务周期及执行时间') }}:
                            </a-col>
                            <a-col :span="21" class="cont">
                                <div>
                                    <a-tag style="opacity: 0.6;"
                                        :color="cycleTypeColor.get(projectStrategy.raw_cycle_type)">{{
                                            cycleType.get(projectStrategy.raw_cycle_type) }}</a-tag>
                                    <span v-if="Array.isArray(projectStrategy.raw_cycles)">{{
                                        projectStrategy.raw_cycles.join(',') }}</span>
                                    <span v-else>{{
                                        projectStrategy.raw_cycles }}</span>
                                </div>
                                <!-- 时间段 -->
                                <div v-if="projectStrategy.raw_time_type == '1'">
                                    <span style="margin-right: 16px;"
                                        v-if="projectStrategy.raw_start_time && projectStrategy.raw_end_time">{{
                                            projectStrategy.raw_start_time }} - {{ projectStrategy.raw_end_time }}</span>
                                    <span v-if="projectStrategy.raw_every_few_type == '1'">{{ $t('每') }}{{
                                        projectStrategy.raw_every_few
                                    }}{{ $t('分钟') }}{{ $t('执行一次') }}</span>
                                    <span v-if="projectStrategy.raw_every_few_type == '2'">{{ $t('每') }}{{
                                        projectStrategy.raw_every_few
                                    }}{{ $t('小时') }}{{ $t('执行一次') }}</span>
                                </div>
                                <!-- 时间点 -->
                                <div v-if="projectStrategy.raw_time_type == '2'">{{ projectStrategy.raw_time }}{{
                                    $t('执行一次') }}</div>
                            </a-col>
                        </a-row>
                        <a-row class="size14 mt-14">
                            <a-col :span="3" class="shallow">
                                {{ $t('最大保存数量') }}:
                            </a-col>
                            <a-col :span="21" class="cont">
                                {{ $t('保留最近') }}{{ projectStrategy.reserve_count }}{{ $t('个') }}
                            </a-col>
                        </a-row>
                    </div>
                </div>
            </a-row>

            <a-row style="margin:1.5em 1.5em">
                <div style="background-color:white;box-shadow:0 0 6px 2px rgba(0,0,0,0.15);padding-bottom:15px;">
                    <div style="padding:17px 22px;" class="size14 cont">{{ $t('保护任务日志') }}</div>
                    <div class="line"></div>
                    <div style="padding:17px 22px;position:relative;">
                        <a-range-picker show-time @change="onChange" valueFormat="YYYY-MM-DD HH:mm:ss" @ok="handleTime">
                            <a-icon slot="suffixIcon" type="smile" />
                        </a-range-picker>

                        <a-radio-group v-model="result" style="margin-left: 16px;" @change="radioChange">
                            <a-radio-button v-for="item of stateList" :value="item.value" :key="item.value">{{ item.label
                            }}</a-radio-button>
                        </a-radio-group>

                        <a-button :disabled="deleteList.length == 0" type='primary' @click="handleDelete" style="position: absolute;right: 22px">
                            <Iconfont class="icon button-icon-style" type="icon-error16f"></Iconfont>
                            {{ $t('删除保护任务日志') }}
                        </a-button>

                        <a-spin :spinning="loading">
                            <div class="log" style="margin-top: 8px;">
                                <a-checkbox v-show="isShow" style="margin-top: 8px;" :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange">
                                    {{ $t('选择全部') }}
                                </a-checkbox>
                                <div v-for="(value, key, index) in taskLog" :key='index'>
                                    <div class="title">{{ timeFormat(key) }}</div>
                                    <div v-for="item of value"
                                        style="height: 48px;line-height: 48px;border-radius: 4px;margin-top: 12px">
                                        <a-row>
                                            <div
                                                :style="{ borderRadius: '0 0 24px 0', backgroundColor: stateDot.get(item.result), width: '12px', height: '12px', position: 'absolute' }">
                                            </div>
                                            <div :style="{ backgroundColor: stateColor.get(item.result), display: 'flex' }">
                                                <a-col :span="6">
                                                    <a-checkbox @change="checkChange" :id="item.id + ''" :checked="item.checked"
                                                        :disabled="!item.can_delete">
                                                        {{ item.start_time.slice(0, 19) }}
                                                    </a-checkbox>
                                                </a-col>
                                                <a-col :span="6">
                                                    {{ gateway }}
                                                </a-col>
                                                <a-col :span="6">
                                                    <span class="dot"
                                                        :style="{ backgroundColor: stateDot.get(item.result) }"></span>
                                                    <span style="margin-left: 8px;margin-right: 8px;">{{ stateType.get(item.result) }}</span>
                                                    <a-tooltip placement='top' v-if="item.result == 3">
                                                        <template slot='title'>
                                                            <span>{{ $t('查看原因') }}</span>
                                                        </template>
                                                        <Iconfont class="icon table-operation-icon" type="icon-view16f" @click="handleFail(item)">
                                                        </Iconfont>
                                                    </a-tooltip>                                                
                                                </a-col>
                                                <a-col :span="6">
                                                    {{ $t('持续时间') }}：{{ secondTransform(item.duration) }}
                                                </a-col>
                                            </div>
                                        </a-row>
                                    </div>
                                </div>
                            </div>
                        </a-spin>

                    </div>
                </div>
            </a-row>
        </a-row>

        <taskFail ref="failRef" />
    </div>
</template>
<script>
import taskFail from './taskFail.vue';
import NoAuthPage from '@/components/common/NoAuthPage'
import EmptyData from '@/components/common/EmptyData'
import moment from 'moment';

export default {
    components: { EmptyData, NoAuthPage, taskFail },
    data() {
        return {
            name: '',
            loading: false,
            projectTask: {},
            projectStrategy: {},
            taskLog: {},
            cycleType: new Map([
                [1, "每日"],
                [2, "每周"],
                [3, "每月"],
            ]),
            cycleTypeColor: new Map([
                [1, "#006db8"],
                [2, "#059db3"],
                [3, "#6634b3"],
            ]),
            stateList: [
                { value: '', label: '全部' },
                { value: 1, label: '进行中' },
                { value: 2, label: '成功' },
                { value: 3, label: '失败' },
            ],
            stateType: new Map([
                [1, "进行中"],
                [2, "成功"],
                [3, "失败"],
            ]),
            stateColor: new Map([
                [1, "#f5f9fc"],
                [2, "#f5fbfc"],
                [3, "#fdf6f8"],
            ]),
            stateDot: new Map([
                [1, "#006db8"],
                [2, "#059db3"],
                [3, "#cf1b47"],
            ]),
            gateway: '',
            end_time: '',
            start_time: '',
            result: '',
            deleteList: [],
            indeterminate: false,
            checkAll: false,
            checkedList: [],
            dataList: [],
        }
    },
    async mounted() {
        this.name = this.$route.query.name
        this.getList()
    },
    computed: {
        isShow() {
            if (this.dataList.length == 0) return false
            else if (this.result == 1) return false
            // else if (this.dataList.every(item => item.can_delete == false) == true) return false
            else if (this.dataList.every(item => !item.can_delete)) return false
            else return true
        }
    },
    methods: {
        async getList() {
            this.loading = true
            const item = {
                task_id: this.$route.query.id,
                start_time: this.start_time,
                end_time: this.end_time,
                result: this.result,
            }
            const { data } = await this.$api.data.getTaskDetailApi(item)
            this.projectTask = data.project_task
            this.projectStrategy = data.project_strategy
            let obj = {}
            data.items.forEach(item => {
                if (!obj[item.start_time.slice(0, 10)]) {
                    obj[item.start_time.slice(0, 10)] = [item]
                } else {
                    obj[item.start_time.slice(0, 10)].push({ ...item, checked: false })
                }
            })
            this.taskLog = obj
            this.gateway = data.project_gateway
            this.checkedList = data.items.filter(item => item.can_delete).map(item => item.id)
            this.dataList = data.items
            this.loading = false
        },
        async handleDelete() {
            this.loading = true
            let _this = this
            this.$confirm({
                title: this.$t('删除保护任务日志'),
                content: this.$t('删除保护任务日志') + this.$t('后，将无法恢复！您确定要删除吗？'),
                cancelText: this.$t('Cancel'),
                okText: this.$t('Sure'),
                okType: 'danger',
                icon: 'close-circle',
                async onOk() {
                    const { data } = await _this.$api.data.deleteTaskDetailApi({ del_ids: _this.deleteList })
                    _this.model(data.id) //返回模板
                    _this.notice(data.id, data.params, data.flag) //通知列表显示
                    if (data.flag == '0') _this.getList()
                },
                onCancel() {
                }
            })
            this.loading = false
        },
        handleNavigate() {
            this.$router.push({ path: '/protect_task' })
        },
        onChange(date, dateString) {
            this.start_time = date[0]
            this.end_time = date[1]
        },
        handleTime() {
            this.getList()
        },
        radioChange() {
            this.getList()
        },
        handleFail(item) {
            this.$refs.failRef.isShow = true
            this.$refs.failRef.reason = item.failed_result.replace(/\n/g, "<br/>")
        },
        secondTransform(second) {
            let d = moment.duration(second, 'seconds');
            let result = Math.floor(d.asDays()) + '天' + d.hours() + '时' + d.minutes() + '分' + d.seconds() + '秒'
            return result
        },
        timeFormat(item) {
            String.prototype.replaceAt = function (index, replacement) {
                return this.substring(0, index) + replacement + this.substring(index + replacement.length);
            }
            const result = item.replaceAt(4, '年').replaceAt(7, '月') + '日'
            return result
        },
        checkChange({ target: { checked, id } }) {
            const index = this.deleteList.findIndex(item => item == id)
            if (index == -1) this.deleteList.push(Number(id))
            else this.deleteList.splice(index, 1)
            for (const key in this.taskLog) {
                this.taskLog[key].map(item => {
                    if (item.id == id) {
                        item.checked = !item.checked
                    }
                })
            }
            this.indeterminate = !!this.deleteList.length && this.deleteList.length < this.checkedList.length;
            this.checkAll = this.deleteList.length === this.checkedList.length;
        },
        onCheckAllChange({ target: { checked }}) {
            this.checkAll = checked
            if (checked) {
                this.deleteList = this.checkedList
                for (const key in this.taskLog) {
                    this.taskLog[key].map(item => {
                        if (item.can_delete) item.checked = true
                    })
                }
            } else {
                this.deleteList = []
                for (const key in this.taskLog) {
                    this.taskLog[key].map(item => {
                        if (item.can_delete) item.checked = false
                    })
                }
            }
        },
    }
}
</script>


<style scoped>
.size14 {
    font-size: 14px;
}

.line {
    width: 100%;
    border-bottom: solid 1px #cccccc;
    line-height: 0.9;
}

.shallow {
    color: #666666;
}

.cont {
    color: #333333;
    /* font-weight: bolder; */
}

.ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled) {
    color: #1E7EBF;
    border-color: #1E7EBF
}

.log {
    height: 300px;
    overflow-y: auto;
}

.log::-webkit-scrollbar {
    /*高宽分别对应横竖滚动条的尺寸*/
    width: 10px;
    height: 1px;
}

.title {
    margin-top: 16px;
    width: 121px;
    height: 24px;
    background-color: #f0f3f5;
    border-radius: 12px;
    text-align: center;
    color: #333333;
}
</style>
